package de.kardass.jsmatep.in.validation;

import de.kardass.jsmatep.schema.jSmaTePImportConfig.RecordImportConfigType;

public class VariableLengthRecordValidator extends AbstractRecordValidator {
	
	private final boolean doValidateMinLength;
	private final int minLength;
	private final boolean doValidateMaxLength;
	private final int maxLength;

	public VariableLengthRecordValidator(RecordImportConfigType importConfig) {
		super(importConfig);
		doValidateMinLength = 
			importConfig.getType().getVariableLength().getMinRecordLength() != null;
		doValidateMaxLength = 
			importConfig.getType().getVariableLength().getMaxRecordLength() != null;
		minLength = 
			doValidateMinLength ? importConfig.getType().getVariableLength().getMinRecordLength().intValue() : -1;
		maxLength = 
			doValidateMaxLength ? importConfig.getType().getVariableLength().getMaxRecordLength().intValue() : -1;
	}

	public void validateRecordVsConfig(String record) {
		validateMinRecordLength(record);
		validateMaxRecordLength(record);
	}

	/**
	 * Validates the max. record length.
	 * 
	 * @param record
	 * @param importConfig
	 * @throws IllegalRecordLengthException
	 */
	private void validateMaxRecordLength(String record) throws IllegalRecordLengthException {
		if (doValidateMaxLength) {
			if (record != null && record.length() > this.maxLength) {
				throw new IllegalRecordLengthException(
						"Max. record length violation, expected max. record length " 
							+ maxLength + ", got " + record.length(), record); 
			}
		}
	}

	/**
	 * Validates the min. record length.
	 * 
	 * @param record
	 * @param importConfig
	 * @throws IllegalRecordLengthException
	 */
	private void validateMinRecordLength(String record) throws IllegalRecordLengthException {
		if (doValidateMinLength) {
			if (record == null || record.length() < this.minLength) {
				throw new IllegalRecordLengthException(
						"Min. record length violation, expected min. record length " 
							+ minLength + ", got " + record.length(), record); 
			}
		}
	}

}
